package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;

import com.robot.admin.client.AgentClient;
import com.robot.admin.client.MemberClient;
import com.robot.admin.pojo.Admin;
import com.robot.admin.pojo.client.Agent;
import com.robot.admin.pojo.client.AgentApply;
import com.robot.admin.service.AdminService;
import com.robot.admin.util.SendMessageUtil;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.UpdateUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/agent_apply")
public class AgentApplyController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private MemberClient memberClient;
    @Autowired
    private AgentClient agentClient;

    @Autowired
    private SendMessageUtil sendMessageUtil;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Admin adminInDb = adminService.findById(claims.getId());
        logger.info("adminInDb=" + adminInDb);
        if (adminInDb == null) {
            return new Result(StatusCode.ERROR_ADMIN_DOES_NOTE_EXIST);
        }

        searchMap.put("deletedAt", null);
        String agentApplyPage = memberClient.thirdFindAgentApplyBySearch(searchMap, page, size);
        logger.info("agentApplyPage=" + agentApplyPage);
        return new Result(StatusCode.SUCCESS_QUERY, JSON.parse(agentApplyPage));
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findAgentById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Admin adminInDb = adminService.findById(claims.getId());
        logger.info("adminInDb=" + adminInDb);
        if (adminInDb == null) {
            return new Result(StatusCode.ERROR_ADMIN_DOES_NOTE_EXIST);
        }

        AgentApply agentApplyInDb = JSON.parseObject(memberClient.thirdFindAgentApplyById(id), AgentApply.class);
        logger.info("agentApplyInDb=" + agentApplyInDb);
        if (agentApplyInDb == null) {
            return new Result(StatusCode.ERROR_AGENT_DOES_NOTE_EXIST);
        }
        if (agentApplyInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR, "该代理商申请单已被删除");
        }
        return new Result(StatusCode.SUCCESS_QUERY, agentApplyInDb);
    }

    /**
     * 审核功能
     *
     * @param agentApply
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody AgentApply agentApply, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Admin adminInDb = adminService.findById(claims.getId());
        logger.info("adminInDb=" + adminInDb);
        if (adminInDb == null) {
            return new Result(StatusCode.ERROR_ADMIN_DOES_NOTE_EXIST);
        }


        if (agentApply.getStatus() == null) {
            return new Result(StatusCode.ERROR_STATUS_REQUIRED);
        }

        AgentApply agentApplyInDb = JSON.parseObject(memberClient.thirdFindAgentApplyById(id), AgentApply.class);
        logger.info("agentApplyInDb=" + agentApplyInDb);
        if (agentApplyInDb == null) {
            return new Result(StatusCode.ERROR_AGENT_DOES_NOTE_EXIST);
        }
        if (agentApplyInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR, "该代理商申请单已被删除");
        }
        String agentApplyStatusSuccess = "1";
        if (agentApplyStatusSuccess.equals(agentApplyInDb.getStatus())) {
            return new Result(StatusCode.ERROR, "该代理商申请单已审核通过了");
        }

        String agentApplyStatusFailed = "2";
        if (agentApplyStatusSuccess.equals(agentApply.getStatus())) {
            //判断agent是否存在
            Agent agentInDb = JSON.parseObject(agentClient.thirdFindAgentByPhone(agentApplyInDb.getPhone()), Agent.class);
            logger.info("agentInDb=" + agentInDb);
            if (agentInDb != null) {
                return new Result(StatusCode.ERROR, "手机号已被使用,请换个手机号");
            }
            //处理审核通过的业务 根据apply_新增一个代理商,用apply 填充一个agent对象
            Agent agent = new Agent();
            logger.info("agent=" + agent.toString());
            logger.info("agentApplyInDb=" + agentApplyInDb.toString());
            UpdateUtil.copyNonNullProperties(agentApplyInDb, agent);
            //提交agent进行新增
            agentApplyInDb.setStatus(agentApplyStatusSuccess);
            agentClient.thirdAddAgent(JSON.toJSONString(agentApplyInDb));
        } else if (agentApplyStatusFailed.equals(agentApply.getStatus())) {
            if (agentApply.getRemark() == null || "".equals(agentApply.getRemark())) {
                return new Result(StatusCode.ERROR, "拒绝的原因必填");
            }
            agentApplyInDb.setRemark(agentApply.getRemark());
            agentApplyInDb.setStatus(agentApplyStatusFailed);
        } else {
            return new Result(StatusCode.ERROR, "审核状态错误");
        }
        agentApplyInDb.setUpdatedAt(LocalDateTime.now());

        memberClient.thirdUpdateAgentApplyByAgentApply(JSON.toJSONString(agentApplyInDb), id);
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 消息推送
     *
     * @param map
     * @return
     */
    @PostMapping("messagePush")
    public Result sendSms(@RequestBody Map map) {
        Map<String, Object> resultMap = sendMessageUtil.sendMessage(map);

        return new Result(StatusCode.SUCCESS_SEND);
    }
}
